#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "gui.h"
#include "mtcore.h"

enum states {q0, q1, q2, q3, q4, q5, q6};

int *create_tape(int m, int n) {

	int tape_lgt = m + n + 2;	
	int* tape = malloc(tape_lgt * sizeof *tape);
	
	int i;
	for(i = 0; i < tape_lgt; i++)
		tape[i] = 0;

	tape[m] = 1;

	tape[m+n+1] = 8;

	return (int*) tape;
}

void ch_fprint_tape(int *tape, int tape_lgt, FILE *out) {

	int state = q0;
	int pos = 0;
	
	while(1) {
		inst_desc(tape, tape_lgt, pos, state, out);	
		if(state == q0) {
			if(tape[pos] == 0) {
				tape[pos] = 8;
				state = q1;
				pos+=1;
			}
			else if(tape[pos] == 1) {
				tape[pos] = 8;
				state = q5;
				pos+=1;
			}
			else if(tape[pos] == 8) {
				break;
			}
		}
		else if(state == q1) {
			if(tape[pos] == 0) {
				tape[pos] = 0;
				state = q1;
				pos+=1;
			}
			else if(tape[pos] == 1) {
				tape[pos] = 1;
				state = q2;
				pos+=1;
			} else if(tape[pos] == 8) {
				break;
			}
		}
		else if(state == q2) {
			if(tape[pos] == 0) {
				tape[pos] = 1;
				state = q3;
				pos-=1;
			}
			else if(tape[pos] == 1) {
				tape[pos] = 1;
				state = q2;
				pos+=1;
			}
			else if(tape[pos] == 8) {
				tape[pos] = 8;
				state = q4;
				pos-=1;
			}
		}
		else if(state == q3) {
			if(tape[pos] == 0) {
				tape[pos] = 0;
				state = q3;
				pos-=1;
			}
			else if(tape[pos] == 1) {
				tape[pos] = 1;
				state = q3;
				pos-=1;
			}
			else if(tape[pos] == 8) {
				tape[pos] = 8;
				state = q0;
				pos+=1;
			}
		}
		if(state == q4) {
			if(tape[pos] == 0) {
				tape[pos] = 0;
				state = q4;
				pos-=1;
			}
			else if(tape[pos] == 1) {
				tape[pos] = 8;
				state = q4;
				pos-=1;
			}
			else if(tape[pos] == 8) {
				tape[pos] = 0;
				state = q6;
				pos+=1;
			}
		}
		else if(state == q5) {
			if(tape[pos] == 0) {
				tape[pos] = 8;
				state = q5;
				pos+=1;
			}
			else if(tape[pos] == 1) {
				tape[pos] = 8;
				state = q5;
				pos+=1;
			}
			else if(tape[pos] == 8) {
				tape[pos] = 1;
				state = q6;
				pos+=1;
			}
		}

		else if(state == q6) {
			break;
		}



		}
	
	}

int count(int *tape, int tape_lgt) {
	int i, c;

	for(i = 0, c = 0; i < tape_lgt; i++) {
		if(tape[i] == 0)
			c++;
	}
	return c;
}
